import $ from 'jquery';
import Button from './Button';

export default class ColorButton extends Button {

  renderMenu() {
    $(`
    <ul class="color-list">
      <li><a href="javascript:;" class="font-color font-color-1"></a></li>
      <li><a href="javascript:;" class="font-color font-color-2"></a></li>
      <li><a href="javascript:;" class="font-color font-color-3"></a></li>
      <li><a href="javascript:;" class="font-color font-color-4"></a></li>
      <li><a href="javascript:;" class="font-color font-color-5"></a></li>
      <li><a href="javascript:;" class="font-color font-color-6"></a></li>
      <li><a href="javascript:;" class="font-color font-color-7"></a></li>
      <li><a href="javascript:;" class="font-color font-color-default"></a></li>
    </ul>
    `).appendTo(this.menuWrapper);
    this.menuWrapper.on('mousedown', '.color-list', e => false);
    return this.menuWrapper.on('click', '.font-color',  e => {
      let rgb;
      this.wrapper.removeClass('menu-on');
      let $link = $(e.currentTarget);
      if ($link.hasClass('font-color-default')) {
        let $p = this.editor.body.find('p, li');
        if (!($p.length > 0)) return;
        rgb = window.getComputedStyle($p[0], null).getPropertyValue('color');
      } else {
        rgb = window.getComputedStyle($link[0], null).getPropertyValue('background-color');
      }
      let hex = this._convertRgbToHex(rgb);
      if (!hex) return;
      let range = this.editor.selection.range();
      if (!$link.hasClass('font-color-default') && range.collapsed) {
        let textNode = document.createTextNode(this._t('coloredText'));
        range.insertNode(textNode);
        range.selectNodeContents(textNode);
        this.editor.selection.range(range);
      }
      document.execCommand('styleWithCSS', false, true);
      document.execCommand('foreColor', false, hex);
      document.execCommand('styleWithCSS', false, false);
      if (!this.editor.util.support.oninput) return this.editor.trigger('valuechanged');
    });
  }

  _convertRgbToHex(rgb) {
    let match = (/rgb\((\d+),\s?(\d+),\s?(\d+)\)/g).exec(rgb);
    if (!match) return '';
    let rgbToHex = (r, g, b) => {
      let componentToHex = c => {
        let hex;
        hex = c.toString(16);
        if (hex.length === 1) {
          return `0${hex}`;
        } else {
          return hex;
        }
      };
      return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`;
    };
    return rgbToHex(match[1] * 1, match[2] * 1, match[3] * 1);
  }
}

ColorButton.prototype.name = 'color';
ColorButton.prototype.icon = 'tint';
ColorButton.prototype.disableTag = 'pre';
ColorButton.prototype.menu = true;

